package cn.bqjr.eily.samples.common.mybatis.plus;

import cn.bqjr.eily.samples.entity.BasePO;
import cn.bqjr.eily.web.utils.SecurityUtils;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 公共字段自动填充
 */
public class CommonFieldFillHandler extends MetaObjectHandler {
    /**
     * insert 填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (isInstanceofBasePO(metaObject)
                && null == getFieldValByName(BasePO.CREATEDDATE, metaObject)) {
            setFieldValByName(BasePO.VALID, true, metaObject);  // 是否有效
            setFieldValByName(BasePO.CREATEDDATE, new Date(), metaObject); //创建时间
            setFieldValByName(BasePO.CREATEDBY, SecurityUtils.getLocalUserId(), metaObject);  //创建人
        }
    }

    /**
     * update 填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (isInstanceofBasePO(metaObject)) {
            setFieldValByName(BasePO.LASTUPDATEDDATE, new Date(), metaObject);  //更新时间
            setFieldValByName(BasePO.LASTUPDATEDBY, SecurityUtils.getLocalUserId(), metaObject); //更新人
        }
    }

    /**
     * 是否为BasePO子类
     * @param metaObject
     * @return
     */
    private boolean isInstanceofBasePO(MetaObject metaObject) {
        Object obj = metaObject.getOriginalObject();
        if (null != obj) {
            if(obj instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) obj;
                if (map.containsKey("et")) {
                    return map.get("et") instanceof BasePO;
                }
            }
            return obj instanceof BasePO;
        }
        return false;
    }
}
